package de.fzi.kasma.learner.data;

import java.util.Iterator;
import java.util.Set;

import de.fzi.kasma.learner.path.PathEdge;

import edu.unika.aifb.graphindex.data.Table;
import edu.unika.aifb.graphindex.index.DataIndex;
import edu.unika.aifb.graphindex.index.IndexReader;
import edu.unika.aifb.graphindex.query.StructuredQuery;
import edu.unika.aifb.graphindex.searcher.structured.VPEvaluator;
import edu.unika.aifb.graphindex.storage.StorageException;

public class Dataset {
	
	private IndexReader m_ir;
	private DataIndex m_di;
	private String m_pprob;
	private String m_nprob;
	private VPEvaluator eval;
	private int numberOfExamples;
	private Data[] allData;


	public Dataset(IndexReader ir, String pos, String neg) throws Exception{
		m_ir=ir;
		m_di=ir.getDataIndex();
		this.m_pprob=pos;
		this.m_nprob=neg;
		this.eval = new VPEvaluator(ir);
		setNumberOfExamples();
		setAllData();
		
	}
	
	
	public Iterator<String[]> getPositiveExamples() throws Exception{
		return m_di.iterator(m_pprob);
	}

	public Iterator<String[]> getNegativeExamples() throws Exception{
		return m_di.iterator(m_nprob);
	}

	
	public IndexReader getIndexReader() {
		return m_ir;
	}


	// TODO 
	public boolean querySuccessful(Data x, Set<PathEdge> edgeSet) throws StorageException {
		
		StructuredQuery q = new StructuredQuery("q1");

		for(PathEdge e : edgeSet){

		q.addEdge(e.getSource().toString(), e.getProperty(),  e.getTarget().toString());

		}
		q.addEdge(x.getSourceNode().toString(), "?property", x.getTargetNode().toString());

		return (!(eval.evaluate(q).rowCount()==0)? true : false);
		
		
	}


	public void setAllData() throws Exception {

		Data[] orderedData = new Data[numberOfExamples];

		Iterator<String[]> it = getPositiveExamples();
		int i =0;
		for (i =0; it.hasNext(); i++){
			
			Data d = new Data();
			String[] str = it.next();
			d.setSourceNode(str[0]);
			d.setTargetNode(str[2]);
			Label positive = new Label();
			positive.setValue(1.0);
			d.setLabel(positive);		
			orderedData[i] = d;						
		}
		it = getNegativeExamples();
		for(int j = i; it.hasNext(); j++){
			
			Data d = new Data();
			String[] str = it.next();
			d.setSourceNode(str[0]);
			d.setTargetNode(str[2]);
			Label negative = new Label();
			negative.setValue(-1.0);
			d.setLabel(negative);		
			orderedData[j] = d;	
			
		}
		
		allData = orderedData;
	}
	
	public Data[] getAllData(){

		return allData;
		
	}


	public void setNumberOfExamples() throws Exception {

       int number = 0;

       Iterator<String[]> it = getPositiveExamples();
       while(it.hasNext()){
    	   it.next();
    	   number++;
       }
       it = getNegativeExamples();
       while(it.hasNext()){
    	   it.next();
    	   number++;
       }
       numberOfExamples = number;
       
	}
	
	public int getNumberOfExamples(){
		
		return numberOfExamples;
		
	}

}
